package cn.wolfcode.mq.listener;

import cn.wolfcode.core.WebSocketServer;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.websocket.Session;

/**
 * 监听购买订单的订单编号监听器
 */
@RocketMQMessageListener(
        consumerGroup = MQConstant.ORDER_RESULT_CONSUMER_GROUP,
        topic = MQConstant.ORDER_RESULT_TOPIC
)
@Component
@Slf4j
public class OrderResultMessageListener implements RocketMQListener<OrderMQResult> {

    /**
     * @param orderMQResult 订单创建完成的消息结果
     */
    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        String json = JSON.toJSONString(orderMQResult);
        log.info("[订单结果] 收到创建订单结果消息:{}", json);
        //获取token
        String token = orderMQResult.getToken();
        try {
            int count = 0;
            Session session = null;
            do {
                //根据token获取Session
                session = WebSocketServer.SESSION_MAP.get(token);
                //如果MQ先监听到消息，而websocket还没与前端建立连接，此时无法将消息推送到前台去
                //解决方案：重试机制,当session为null时，多尝试几次去拿,如果几次后拿不到，则证明连接失败
                if (session != null) {
                    //通过Session对象,把数据写到前端
                    session.getBasicRemote().sendText(json);
                    break;
                }
                count++;
                log.info("[订单结果] 第{}次查询 session 对象获取失败,准备下一次获取...", count);
                //睡一会再拿
                Thread.sleep(300);
            } while (count <= 5);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
